package cn.mengfly.testnrz.netty.protobuf;

import cn.mengfly.testnrz.util.BootStrapUtil;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.protobuf.ProtobufDecoder;
import io.netty.handler.codec.protobuf.ProtobufVarint32FrameDecoder;

/**
 * @author Mengfly
 */
public class ProtoBufServer {

    ServerBootstrap b = new ServerBootstrap();

    public void runServer() {
        EventLoopGroup bossLoopGroup = new NioEventLoopGroup();
        EventLoopGroup workerLoopGroup = new NioEventLoopGroup();
        try {
            BootStrapUtil.initServer(b, bossLoopGroup, workerLoopGroup);
            b.childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                    ch.pipeline().addLast(new ProtobufVarint32FrameDecoder());
                    ch.pipeline().addLast(new ProtobufDecoder(MsgProtos.Msg.getDefaultInstance()));
                    ch.pipeline().addLast(new ProtobufBusinessDecoder());
                }
            });
            ChannelFuture sync = b.bind().sync();
            ChannelFuture closeFuture = sync.channel().closeFuture();
            closeFuture.sync();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            bossLoopGroup.shutdownGracefully();
            workerLoopGroup.shutdownGracefully();
        }


    }

    private static class ProtobufBusinessDecoder extends ChannelInboundHandlerAdapter {

        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) {
            System.out.println(msg);
//            MsgProtos.Msg protoMsg = ((MsgProtos.Msg) msg);
//            System.out.println("收到一个Msg数据包");
//            System.out.println("id = " + protoMsg.getId());
//            System.out.println("content = " + protoMsg.getContent());
//            super.channelRead(ctx, msg);
        }
    }

    public static void main(String[] args) {
        new ProtoBufServer().runServer();
    }
}
